<template>
	<el-form :model="goodForm" ref="goodFormRef" :rules="rules" label-width="80px">
		<el-form-item label="店铺名称">
			<el-input v-model="goodForm.shop"></el-input>
		</el-form-item>
		<el-form-item label="产品名称" prop="product">
			<el-input v-model="goodForm.product"></el-input>
		</el-form-item>

		<el-form-item label="产品分类">
			<el-select v-model="goodForm.categoryId" clearable placeholder="选择产品分类">
				<el-option v-for="item in category" :key="item.id" :label="item.name" :value="item.id" />
			</el-select>
		</el-form-item>

		<el-form-item label="现价">
			<el-input v-model="goodForm.price"></el-input>
		</el-form-item>
		<el-form-item label="原价">
			<el-input v-model="goodForm.oldprice"></el-input>
		</el-form-item>
		<el-form-item label="图片">
			<!-- 
                list-type: picture-card 卡片样式
                action: 图片上传url地址
                auto-upload: 是否自动上传，true自动上传，选中图片直接上传到action指定url
                show-file-list: false单文件上传，true支持多文件上传
                before-upload: 上传前回调, 当前auto-upload为true时执行,回调函数中返回false终止上传
             -->
			<el-upload
				list-type="picture-card"
				action="#"
				:auto-upload="true"
				:show-file-list="false"
				:before-upload="beforeAvatarUpload"
			>
				<img v-if="imageUrl" :src="imageUrl" class="avatar" />
				<el-icon v-else><Plus /></el-icon>
			</el-upload>
		</el-form-item>

		<el-form-item label="上下架">
			<el-radio-group v-model="goodForm.putaway">
				<el-radio :label="1">上架</el-radio>
				<el-radio :label="0">下架</el-radio>
			</el-radio-group>
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="onSubmit">确定</el-button>
			<el-button type="primary" @click="onClose">关闭</el-button>
		</el-form-item>
	</el-form>
</template>

<script>
import { api } from '@/api/index'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { filterImageUrl } from '@/utils'
const { RequestCategoryList, RequestProductAdd, RequestProductUpdate } = api
export default {
	components: {
		Plus
	},
	props: ['goods', 'type'],
	emits: ['close'],
	data() {
		return {
			goodForm: {
				shop: '',
				product: '',
				price: '',
				oldprice: '',
				picture: '',
				putaway: 1,
				categoryId: ''
			},
			category: [],
			rules: {
				product: [
					{
						required: true,
						message: '请输入产品名称',
						trigger: 'blur'
					}
				]
			},
			imageUrl: '', //图片预览地址
			imageFile: null //上传图片文件
		}
	},
	created() {
		if (this.type === 'EDIT') {
			this.goodForm = { ...this.goods }
			this.imageUrl = this.filterUrl(this.goodForm.picture)
		}
		this.getCategoryList()
	},
	methods: {
		filterUrl(url) {
			return url?.indexOf('http') === -1 ? import.meta.env.VITE_APP_BASE + url : url
		},
		/**
		 * 分类列表
		 */
		async getCategoryList() {
			const data = await RequestCategoryList()
			const { resultCode, resultInfo } = data
			if (resultCode === 1) {
				this.category = resultInfo.list
			}
		},
		/**
		 * 保存产品
		 *  图片上传http注意事项
		 *     1. post请求
		 *     2. 请求头header 上传内容类型 content-type:multipart/form-data
		 *         headers: { 'Content-Type': 'multipart/form-data' },
		 *     3. FormData
		 *         const formData = new FormData()
		 *         formData.append('product',product)
		 *         formData.append('picture',file)
		 */
		async onSubmit() {
			const formData = new FormData()
			formData.append('categoryId', this.goodForm.categoryId)
			formData.append('product', this.goodForm.product)
			formData.append('picture', this.imageFile)
			formData.append('shop', this.goodForm.shop)
			formData.append('price', this.goodForm.price)
			formData.append('oldprice', this.goodForm.oldprice)
			formData.append('putaway', this.goodForm.putaway)
			// 编辑
			let data
			if (this.type === 'EDIT') {
				formData.append('id', this.goodForm.id)
				data = await RequestProductUpdate(formData)
			} else {
				data = await RequestProductAdd(formData)
			}

			const { resultCode } = data
			if (resultCode === 1) {
				ElMessage({
					message: this.type === 'EDIT' ? '编辑产品成功!' : '添加产品成功!',
					type: 'success'
				})
				this.onClose()
			}
		},
		onClose() {
			this.$emit('close')
		},
		/**
		 * 文件上传之前执行
		 * @param {*} rawFile
		 */
		beforeAvatarUpload(rawFile) {
			const arr = ['image/jpeg', 'image/png', 'image/jpg']
			// 图片格式验证
			if (!arr.includes(rawFile.type)) {
				ElMessage({
					message: '上传图片格式不正确！!',
					type: 'error'
				})
				return false
			}
			// 图片大小验证
			if (rawFile.size / 1024 / 1024 > 2) {
				ElMessage({
					message: '上传图片大小不能超过2M!',
					type: 'error'
				})
				return false
			}

			// 图片预览
			//1. 选中的本地图片转成Base64编码 赋值给 imageUrl
			//2. FileReader 读文件
			this.imageUrl = URL.createObjectURL(rawFile)

			// 上传图片
			this.imageFile = rawFile
			return false // 不向下执行
		}
	}
}
</script>

<style lang="scss" scoped>
.avatar {
	width: 150px;
	height: 150px;
	display: block;
}
</style>
